package com.cxs.xiaomi.web.controller;

import com.cxs.xiaomi.domain.GoodsType;
import com.cxs.xiaomi.domain.User;
import com.cxs.xiaomi.service.GoodsTypeService;
import com.cxs.xiaomi.service.impl.GoodsTypeServiceImpl;
import com.cxs.xiaomi.utils.*;
import cxs.utils.utils.ParamsAsBean;
import cxs.utils.utils.Result;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/9/14  16:13
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@WebServlet(name = "GoodsTypeServlet", urlPatterns = "/goodstypeservlet")
public class GoodsTypeServlet extends BaseServlet {

    private GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();

    public Object goodstypelist(HttpServletRequest request, HttpServletResponse response) {
        List<GoodsType> list = goodsTypeService.goodsTypeList();
        return new Result<>("数据请求成功", 200, list);
    }


    // 管理员
    // 查看商品分类
    public String getGoodsType(HttpServletRequest request, HttpServletResponse response){
        User admin = getAdmin(request, response);
        if(admin != null){
            List<GoodsType> goodsTypeList = goodsTypeService.goodsTypeList();
            request.setAttribute("goodsTypeList",goodsTypeList);
            return "forward:/admin/showGoodsType.jsp";
        }
        return "redirect:/admin/login.jsp";
    }

    // 添加分类
    public String addGoodType(HttpServletRequest request, HttpServletResponse response){
        String typename = request.getParameter("typename");
        if(StringUtil.empty(typename)){
            request.setAttribute("msg","商品名不能为空");
            return "forward:/message.jsp";
        }
        GoodsType goodsType = new GoodsType(null,typename.trim(),1,1);
        goodsTypeService.add(goodsType);
        return "redirect:/goodstypeservlet?method=getGoodsType";
    }

    // 修改分类
    public String updateType(HttpServletRequest request, HttpServletResponse response){
        try {
            GoodsType goodsType = ParamsAsBean.parammeterAsBean(GoodsType.class, request, false);
            if(goodsType != null){
                goodsTypeService.update(goodsType);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/goodstypeservlet?method=getGoodsType";
    }

    // 删除
    public Object deleteType(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        if(StringUtil.empty(id)){
            return Result.failare("id不能为空");
        }
        return goodsTypeService.delete(Integer.parseInt(id.trim())) ?
                Result.OK("删除成功") :
                Result.failare("删除失败");
    }
    // 测试
    public void test(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("测试方法执行");
    }
}
